//
//  WFStatusPictureView.swift
//  WangFangWeiBo
//
//  Created by 王方 on 16/7/15.
//  Copyright © 2016年 wf. All rights reserved.
//

import UIKit

//重用标记
private let PictureViewCellId = "PictureViewCellId"
//每项的间距
private let itemMargin: CGFloat = 5
//每项的宽度
private let itemWidth:CGFloat = (ScreenWidth - 2 * HomeCellMargin - 2 * itemMargin) / 3

class WFStatusPictureView: UICollectionView {
    
    // MARK:  - 定义配图的数据源
    var picUrls:[WFStatusPictureInfo]? {
        didSet{
            messageLabel.text = "\(picUrls?.count ?? 0)"
             let size = calcPictureViewSize((picUrls?.count)!)
            self.snp_updateConstraints { (make) -> Void in
                make.size.equalTo(size)
            }
            self.reloadData()
        }
    }
    
    // MARK:  - 懒加载控件
    private lazy var messageLabel:UILabel = {
        let label = UILabel(textColor: UIColor.greenColor(), fontSize: 15)
        return label
        
    }()
    
    //构造函数
    override init(frame: CGRect, collectionViewLayout layout: UICollectionViewLayout) {
        //假设外界不传layout.我们自己写一个
        let flowLayout = UICollectionViewFlowLayout()
        flowLayout.itemSize = CGSize(width: itemWidth, height: itemWidth)
        flowLayout.minimumLineSpacing = itemMargin
        flowLayout.minimumInteritemSpacing = itemMargin
        super.init(frame: frame, collectionViewLayout: flowLayout)
        setUpUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    // MARK:  - 初始化控件
    private func setUpUI(){
        registerClass(WFStatusCVCell.self, forCellWithReuseIdentifier: PictureViewCellId)
        dataSource = self
        delegate = self
        //观察用label
//        addSubview(messageLabel)
//        messageLabel.snp_makeConstraints { (make) -> Void in
//            make.center.equalTo(self)
//        }
    }
    
    //根据图片个数计算配图大小
    private func calcPictureViewSize(count:Int)->CGSize{
        
        //列数
        let cols = count > 3 ? 3 :count
        //行数
        let rows = (count - 1) / 3 + 1
        
        //计算当前配图的一个宽度
        let width = CGFloat(cols) * itemWidth + CGFloat(cols - 1) * itemMargin
        //计算当前配图的一个高度
        let height = CGFloat(rows) * itemWidth + CGFloat(rows - 1) * itemMargin
        
        return CGSizeMake(width, height)
    }
    
    
}
// MARK:  - 实现数据源代理方法
extension WFStatusPictureView : UICollectionViewDataSource,UICollectionViewDelegate,SDPhotoBrowserDelegate{
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return picUrls?.count ?? 0
    }
    
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(PictureViewCellId, forIndexPath: indexPath) as! WFStatusCVCell

        cell.picInfo = picUrls![indexPath.item]
        
        return cell
    }
    
    //点击单个cell的时候进行放大集成
    func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
//        SDPhotoBrowser *photoBrowser = [SDPhotoBrowser new];
//        photoBrowser.delegate = self;
//        photoBrowser.currentImageIndex = indexPath.item;
//        photoBrowser.imageCount = self.modelsArray.count;
//        photoBrowser.sourceImagesContainerView = self.collectionView;
//        
//        [photoBrowser show];
        print("放大")
        let photoBrowser = SDPhotoBrowser()
        photoBrowser.delegate = self
        photoBrowser.currentImageIndex = indexPath.item
        photoBrowser.imageCount = (picUrls?.count)!
        photoBrowser.sourceImagesContainerView = self
        photoBrowser.show()
        
    }
    
    // MARK:  - 为了集成放大功能,需要实现的代理
    // 返回临时占位图片（即原来的小图）
//    - (UIImage *)photoBrowser:(SDPhotoBrowser *)browser placeholderImageForIndex:(NSInteger)index
//    {
//    // 不建议用此种方式获取小图，这里只是为了简单实现展示而已
//    SDCollectionViewDemoCell *cell = (SDCollectionViewDemoCell *)[self collectionView:self.collectionView cellForItemAtIndexPath:[NSIndexPath indexPathForItem:index inSection:0]];
//    
//    return cell.imageView.image;
//    
//    }
    func photoBrowser(browser: SDPhotoBrowser!, placeholderImageForIndex index: Int) -> UIImage! {
        let cell = self.cellForItemAtIndexPath(NSIndexPath(forItem: index, inSection: 0)) as! WFStatusCVCell
        return cell.imageView.image
    }
    
    // 返回高质量图片的url
//    - (NSURL *)photoBrowser:(SDPhotoBrowser *)browser highQualityImageURLForIndex:(NSInteger)index
//    {
//    NSString *urlStr = [[self.modelsArray[index] thumbnail_pic] stringByReplacingOccurrencesOfString:@"thumbnail" withString:@"bmiddle"];
//    return [NSURL URLWithString:urlStr];
//    }
    func photoBrowser(browser: SDPhotoBrowser!, highQualityImageURLForIndex index: Int) -> NSURL! {
        let urlStr = self.picUrls![index].thumbnail_pic!.stringByReplacingOccurrencesOfString("thumbnail", withString: "bmiddle")
        
        return NSURL(string: urlStr)
        
    }
}

// MARK:  - 自定义cell

class WFStatusCVCell : UICollectionViewCell {
    
    //设置模型
    var picInfo:WFStatusPictureInfo? {
        didSet{
            if let imageUrl = picInfo?.thumbnail_pic {
                imageView.sd_setImageWithURL(NSURL(string: imageUrl), placeholderImage: UIImage(named: "timeline_image_placeholder"))
                
                gifImageView.hidden = !imageUrl.hasSuffix(".gif")
            }
            
            
        }
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setUpUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    // MARK:  -  懒加载图片控件
    private lazy var imageView:UIImageView = {
        let image = UIImageView(image: UIImage(named: "timeline_image_placeholder"))
        //  保证原始图片比例显示, 图片会超出
        image.contentMode = UIViewContentMode.ScaleAspectFill
        //  剪切超出多余部分的图片
        image.clipsToBounds = true
        return image
    }()
    //gif图片
    private lazy var gifImageView:UIImageView = UIImageView(image: UIImage(named: "timeline_image_gif"))
    
    
    //初始化自定义cell里面的控件
    private func setUpUI(){
       contentView.addSubview(imageView)
        contentView.addSubview(gifImageView)
        imageView.snp_makeConstraints { (make) -> Void in
            make.edges.equalTo(contentView).offset(UIEdgeInsetsZero)
        }
        gifImageView.snp_makeConstraints { (make) -> Void in
            make.trailing.equalTo(imageView)
            make.bottom.equalTo(imageView)
        }
    }
}

